package com.juzipi.demo.controller;

import com.juzipi.demo.client.UserClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("users")
//定义全局的熔断 方法
//@DefaultProperties(defaultFallback = "fallbackMethod")
public class UserController {

    @Autowired
    private UserClient userClient;

   /* @Autowired
    private RestTemplate restTemplate;*/

   /* @Autowired
    private DiscoveryClient discoveryClient;*/

    @GetMapping
    @ResponseBody
    //调用方法 声明熔断的方法
    @HystrixCommand //(fallbackMethod = "fallbackMethod")
    public String findUserById(@RequestParam("id")Integer id){
        /*if (id == 7){
            throw new RuntimeException();
        }*/

        /* //获取服务名
        List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
        //解决地址硬编码的问题
        ServiceInstance serviceInstance = instances.get(0);
        return this.restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/"+id, User.class);
        */
        //配置服务名，根据服务名自动选择一个进行调用
        //return this.restTemplate.getForObject("http://service-provider/user/"+id, String.class);
        return this.userClient.findById(id).toString();
    }
    /*//熔断 返回信息，返回值要与被熔断的 数据类型一致
    public String fallbackMethod(){
        return "服务器正忙，请稍后再试";
    }*/
}
